package io.gitee.tziye.core.id;

import io.gitee.tziye.common.RenaiUtil;
import io.gitee.tziye.common.ValueResult;
import io.gitee.tziye.enums.TimePattern;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class RenaiIdSpec {

    private String prefix;
    private TimePattern pattern = TimePattern.YMD;
    private int num = 5;
    private int step = 1;
    private boolean random;

    public RenaiIdSpec(String prefix) {
        this.prefix = prefix;
    }

    public RenaiIdSpec(String prefix, TimePattern pattern) {
        this.prefix = prefix;
        this.pattern = pattern;
    }

    public RenaiIdSpec(String prefix, TimePattern pattern, int num) {
        this.prefix = prefix;
        this.pattern = pattern;
        this.num = num;
    }

    public String time() {
        return pattern.format();
    }

    public int step() {
        if (random) {
            return 1 + RenaiUtil.random(step);
        }
        return step;
    }

    public long returnId(ValueResult result) {
        long seq = result.getLv();
        int len = String.valueOf(seq).length();
        if (len < num) {
            len = num;
        }
        return Long.parseLong(result.getSv() + String.format("%0" + len + "d", seq));
    }

    public String returnCode(ValueResult result) {
        return prefix + returnId(result);
    }
}
